package com.example.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.reggie.common.BaseContext;
import com.example.reggie.common.CustomException;
import com.example.reggie.common.R;
import com.example.reggie.dto.OrdersDto;
import com.example.reggie.entity.*;
import com.example.reggie.mapper.OrdersMapper;
import com.example.reggie.service.*;
import com.sun.org.apache.xpath.internal.operations.Or;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {

    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private AddressBookService addressBookService;

    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired
    private UserService userService;


    /**
     * 保存订单信息
     * @param order
     */
    @Transactional
    @Override
    public void submit(Orders order) {
        Long userId = BaseContext.getCurrentId();

        //获取当前登录用户的默认收货地址数据
        LambdaQueryWrapper<AddressBook> wrapper =new LambdaQueryWrapper<>();
        wrapper.eq(AddressBook::getId,order.getAddressBookId());
        AddressBook addressBook = addressBookService.getOne(wrapper);
        if(addressBook==null){
            throw new CustomException("地址信息有误，不能下单");
        }
        order.setAddress(addressBook.getProvinceName()==null?"":addressBook.getProvinceName()+
                addressBook.getCityName()==null?"":addressBook.getCityName()+
                addressBook.getDistrictName()==null?"":addressBook.getDistrictName()+
                addressBook.getDetail()==null?"":addressBook.getDetail());


        User user = userService.getById(userId);
        order.setUserId(userId);
        order.setUserName(user.getName());
        order.setPhone(addressBook.getPhone());
        order.setConsignee(addressBook.getConsignee());
        order.setOrderTime(LocalDateTime.now());
        order.setCheckoutTime(LocalDateTime.now());
        long orderId= IdWorker.getId();//订单号
        order.setId(orderId);
        order.setNumber(String.valueOf(orderId));
        order.setStatus(2);

        //获取当前登录用户的所有的购物车数据
        LambdaQueryWrapper<ShoppingCart> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId,userId);
        List<ShoppingCart> shoppingCarts = shoppingCartService.list(queryWrapper);
        if(shoppingCarts==null||shoppingCarts.size()==0){
            throw new CustomException("购物车为空，不能下单");
        }
        shoppingCartService.remove(queryWrapper);//清空购物车数据

        List<OrderDetail> orderDetails=new ArrayList<>();
        BigDecimal amount=new BigDecimal(0);
        //将购物车数据加入订单详情表中
        for(ShoppingCart sc:shoppingCarts){
            OrderDetail od=new OrderDetail();
            BeanUtils.copyProperties(sc,od);
            orderDetails.add(od);
            //计算金额
            amount=amount.add(od.getAmount().multiply(new BigDecimal(od.getNumber())));
        }
        order.setAmount(amount);


        this.save(order);

        for(OrderDetail od:orderDetails){
            od.setOrderId(order.getId());
        }

        orderDetailService.saveBatch(orderDetails);

    }

    /**
     * 分页展示订单信息
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public Page<OrdersDto> getPage(int page, int pageSize) {
        //构造分页构造器
        Page<Orders> pageInfo=new Page(page,pageSize);
        Page<OrdersDto> dtoPage=new Page<>();

        //构造条件构造器
        LambdaQueryWrapper<Orders> queryWrapper=new LambdaQueryWrapper();

        queryWrapper.eq(Orders::getUserId,BaseContext.getCurrentId());

        //添加排序条件
        queryWrapper.orderByAsc(Orders::getOrderTime);

        //执行查询
        this.page(pageInfo,queryWrapper);

        BeanUtils.copyProperties(pageInfo,dtoPage,"records");

        List<Orders> orders=pageInfo.getRecords();

        List<OrdersDto> dtos=new ArrayList<>();


        for(Orders od:orders){
            OrdersDto dto=new OrdersDto();
            LambdaQueryWrapper<OrderDetail> wrapper=new LambdaQueryWrapper<>();
            wrapper.eq(OrderDetail::getOrderId,od.getId());
            //设置订单详情
            dto.setOrderDetails(orderDetailService.list(wrapper));
            BeanUtils.copyProperties(od,dto);
            dtos.add(dto);

        }

        dtoPage.setRecords(dtos);

        return dtoPage;
    }

    /**
     * 再来一单
     * @param order
     */
    @Override
    public void again(Orders order) {
        Long userId = BaseContext.getCurrentId();

        //这里主要是获取订单金额
        order=this.getById(order.getId());

        //获取当前登录用户的默认收货地址数据
        LambdaQueryWrapper<AddressBook> wrapper =new LambdaQueryWrapper<>();
        wrapper.eq(AddressBook::getId,order.getAddressBookId());
        AddressBook addressBook = addressBookService.getOne(wrapper);
        if(addressBook==null){
            throw new CustomException("地址信息有误，不能下单");
        }



        order.setAddress(addressBook.getProvinceName()==null?"":addressBook.getProvinceName()+
                addressBook.getCityName()==null?"":addressBook.getCityName()+
                addressBook.getDistrictName()==null?"":addressBook.getDistrictName()+
                addressBook.getDetail()==null?"":addressBook.getDetail());

        //从之前的订单详情中获取对应的商品数据
        LambdaQueryWrapper<OrderDetail> orderDetailLambdaQueryWrapper=new LambdaQueryWrapper<>();
        orderDetailLambdaQueryWrapper.eq(OrderDetail::getOrderId,order.getId());
        List<OrderDetail> orderDetails = orderDetailService.list(orderDetailLambdaQueryWrapper);




        User user = userService.getById(userId);
        order.setUserId(userId);
        order.setUserName(user.getName());
        order.setPhone(addressBook.getPhone());
        order.setConsignee(addressBook.getConsignee());
        order.setOrderTime(LocalDateTime.now());
        order.setCheckoutTime(LocalDateTime.now());
        long orderId= IdWorker.getId();//订单号
        order.setId(orderId);
        order.setNumber(String.valueOf(orderId));
        order.setStatus(2);

        //设置订单详情的id和订单id
        for(OrderDetail od:orderDetails){
            od.setOrderId(order.getId());
            od.setId(null);
        }


        //保存订单信息
        this.save(order);

        //保存订单详情信息
        orderDetailService.saveBatch(orderDetails);

    }
}
